package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// City 城市模型
type City struct {
	BaseModel
	Name      string  `orm:"size(50)" json:"name"`                    // 城市名称
	Code      string  `orm:"size(20)" json:"code"`                    // 城市编码
	Province  string  `orm:"size(50)" json:"province"`                // 所属省份
	Latitude  float64 `orm:"digits(10);decimals(6)" json:"latitude"`  // 纬度
	Longitude float64 `orm:"digits(10);decimals(6)" json:"longitude"` // 经度
	IsHot     int8    `orm:"default(0)" json:"is_hot"`                // 是否热门城市，1:是，0:否
	SortOrder int     `orm:"default(0)" json:"sort_order"`            // 排序
	Status    int8    `orm:"default(1)" json:"status"`                // 状态，1:启用，0:禁用
}

// TableName 设置表名
func (c *City) TableName() string {
	return "ss_city"
}

// GetCityById 根据ID获取城市信息
func GetCityById(id int64) (*City, error) {
	city := &City{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(city)
	return city, err
}

// GetCityList 获取城市列表
func GetCityList(page, pageSize int, filters map[string]interface{}) ([]*City, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(City))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if province, ok := filters["province"].(string); ok && province != "" {
		qs = qs.Filter("province", province)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	if isHot, ok := filters["is_hot"].(int8); ok {
		qs = qs.Filter("is_hot", isHot)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var cities []*City
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&cities)

	return cities, total, err
}

// GetAllCities 获取所有城市（不分页）
func GetAllCities(filters map[string]interface{}) ([]*City, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(City))

	// 应用过滤条件
	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	if isHot, ok := filters["is_hot"].(int8); ok {
		qs = qs.Filter("is_hot", isHot)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 查询所有符合条件的城市
	var cities []*City
	_, err := qs.OrderBy("sort_order", "-id").All(&cities)

	return cities, err
}

// CreateCity 创建城市
func CreateCity(city *City) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(city)
	return id, err
}

// UpdateCity 更新城市信息
func UpdateCity(city *City, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(city, fields...)
	return err
}

// DeleteCity 删除城市（软删除）
func DeleteCity(id int64) error {
	o := orm.NewOrm()
	city := &City{BaseModel: BaseModel{Id: id}}
	err := o.Read(city)
	if err != nil {
		return err
	}

	// 软删除
	city.IsDeleted = 1
	_, err = o.Update(city, "IsDeleted")
	return err
}

// GetCityByName 根据城市名称获取城市信息
func GetCityByName(name string) (*City, error) {
	o := orm.NewOrm()
	city := &City{}

	// 查询未删除且状态正常的城市
	err := o.QueryTable(new(City)).
		Filter("name", name).
		Filter("is_deleted", 0).
		Filter("status", 1).
		One(city)

	return city, err
}
